package com.arpa.wms.scheduled.controller;

import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.map.MapUtil;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.wms.scheduled.domain.dto.OmsOrderSetDTO;
import com.arpa.wms.scheduled.domain.entity.OmsOrderSet;
import com.arpa.wms.scheduled.domain.enums.CommonConst;
import com.arpa.wms.scheduled.domain.enums.StatusEnum;
import com.arpa.wms.scheduled.domain.vo.OmsOrderSetVO;
import com.arpa.wms.scheduled.service.IOmsOrderSetService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * OMS接单设置 Controller
 * </p>
 *
 * @author rfwang
 * @since 2021-08-10
 */
@RestController
@RequestMapping(value="/omsOrderSet", produces = "application/json;charset=UTF-8")
@Log4j2(topic = "business")
public class OmsOrderSetController {

    @Autowired
    private IOmsOrderSetService omsOrderSetService;

    private static final String SUCCESS = "success";

    /**
     * 获取 接单设置 列表
     *
     * @param omsOrderSetDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 接单设置 列表", notes = "获取 接单设置 列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = OmsOrderSetVO.class))
    @NeedLogin
    @GetMapping()
    public Result list(OmsOrderSetDTO omsOrderSetDTO, HttpServletRequest request) {
        try {
            omsOrderSetDTO.setShipmentCode(UserUtil.getLoginWarehouseCodeOrShipmentCode());
            OmsOrderSetVO omsOrderSetVOSum = omsOrderSetService.queryListSum(omsOrderSetDTO);
            List<OmsOrderSetVO> omsOrderSetVOList = omsOrderSetService.queryList(omsOrderSetDTO);

            Page returnPage = new Page(omsOrderSetDTO.getPageNum(),omsOrderSetDTO.getPageSize());
            returnPage.setRecords(omsOrderSetVOList);
            returnPage.setTotal(omsOrderSetVOSum.getTotal());
            returnPage.setSumObject(omsOrderSetVOSum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 添加 接单设置
     *
     * @param entity Customer
     * @param request
     * @return
     */
    @ApiOperation(value = "添加 接单设置 ", notes = "添加 接单设置 ")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PostMapping()
    public Result create(@RequestBody OmsOrderSet entity, HttpServletRequest request) {
        try {

            omsOrderSetService.save(entity);
            return Result.ok("添加成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 修改OMS出库单
     *
     * @param entity OMS出库单
     * @param request
     * @return
     */
    @ApiOperation(value = "修改OMS出库单", notes = "修改OMS出库单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping()
    public Result update(OmsOrderSet entity,HttpServletRequest request) {
        if(StringUtils.isBlank(entity.getCode())){
            return Result.error("code不能为空");
        }
        int updateNum = omsOrderSetService.updateByCode(entity);
        if(updateNum == 0){
            return Result.error("没有更新数据！code:"+entity.getCode());
        }else{
            return Result.ok("修改成功,更新"+updateNum+"条数据！");
        }
    }

    /**
     * 启用接单设置
     *
     * @param codes
     * @param request
     * @return
     */
    @PutMapping("/active")
    public Result active(@RequestParam List<String> codes, HttpServletRequest request) {
        Map<String, Object> result = omsOrderSetService.activeStatus(codes, StatusEnum.ACTIVE);
        //启动任务
        codes.stream().forEach(code -> {
            omsOrderSetService.start(code);
        });
        Integer success = MapUtil.getInt(result, SUCCESS);
        int failNum = codes.size() - success;
        return Result.ok("启用成功" + success + "条；失败" + failNum + "条；");
    }

    /**
     * 停用接单设置
     *
     * @param codes
     * @param request
     * @return
     */
    @PutMapping("/unactive")
    public Result unactive(@RequestParam List<String> codes, HttpServletRequest request) {
        Map<String,Object> result = omsOrderSetService.activeStatus(codes,StatusEnum.UNACTIVE);
        List<OmsOrderSet> orderSetList = omsOrderSetService.list(new LambdaQueryWrapper<OmsOrderSet>().in(OmsOrderSet::getCode, codes));
        Map<String,OmsOrderSet> orderSetMap = orderSetList.stream().collect(Collectors.toMap(OmsOrderSet::getCode, e -> e));
        //停止任务
        codes.stream().forEach(code -> {
            OmsOrderSet omsOrderSet = MapUtil.get(orderSetMap, code, OmsOrderSet.class);
            if (CommonConst.PDD.equals(omsOrderSet.getPlatformCode())) {
                omsOrderSetService.stop(code);
            }
        });
        List<String> msg = MapUtil.get(result,"msg",List.class);
        String message = "";
        if(IterUtil.isNotEmpty(msg)){
            for(String m: msg){
                message+="<br><font color='red'>接单设置【"+m+"】停用失败，库存不为0;</font>";
            }
        }
        return Result.ok("停用成功" + (MapUtil.getInt(result, SUCCESS)==null?0:MapUtil.getInt(result,SUCCESS)) + "条；失败" + (MapUtil.getInt(result,"fail") == null ? 0 : MapUtil.getInt(result,"fail")) + "条；"+message);
    }

    /**
     * 根据任务code => 启动任务
     */
    @RequestMapping("/start")
    public String start(@RequestParam("code") String code) {
        omsOrderSetService.start(code);
        return "start success";
    }

    /**
     * 根据任务code => 停止任务
     */
    @RequestMapping("/stop")
    public String stop(@RequestParam("code") String code) {
        omsOrderSetService.stop(code);
        return "stop success";
    }

    /**
     * 根据任务code => 重启任务
     */
    @RequestMapping("/restart")
    public String restart(@RequestParam("code") String code) {
        omsOrderSetService.restart(code);
        return "restart success";
    }
 }
